package cn.spring.user.dao;

import cn.springweb.domain.User;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;

import javax.sql.DataSource;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;

/**
 * @Author: mayuanbao
 * @Date: 2018-11-23 13:48
 * @Description:
 */
public class UserDaoJdbc implements IUserDao {
    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public void query(final User user) {
        String sql = "select username,password,real_name from user where username = ?";
        JdbcTemplate jt = new JdbcTemplate(dataSource);
        PreparedStatementSetter pss = new PreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps) throws SQLException {
                ps.setString(1, user.getUserName());
            }
        };
        List<User> list = jt.query(sql, pss, new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet rs, int rowNum) throws SQLException {
                String name = rs.getString("username");
                String pwd = rs.getString("password");
                String realName = rs.getString("real_name");
                User user1 = new User();
                user1.setUserName(name);
                user1.setPassword(pwd);
                user1.setRealName(realName);
                return user1;
            }
        });
        System.out.println(">>>" + list);
    }
    @Override
    public void save(User user) {
        String sql = "insert into user (id,name,age) values(?,?,?)";
        String sql1 = "insert into user (id,name,age) values(?,?,?";
        JdbcTemplate jt = new JdbcTemplate(dataSource);
        jt.update(sql, UUID.randomUUID().toString().replace("-", ""), user.getUserName(), user.getPassword());
        jt.update(sql1, UUID.randomUUID().toString().replace("-", ""), "jack", 11);
    }
}
